<?php
namespace app\index\controller;

use app\index\model\Customer;
use app\index\model\UsersLog;
use app\index\model\Express;
use app\index\model\Recharge;
use app\mall\model\MallBraSize;
use app\mall\model\MallGoodsItem;
use app\mall\model\MallSubscription;
use app\mall\model\MallUserActionCollect;
use app\mall\model\MallUsers;
use app\mall\service\ConfigService;
use app\mall\service\EmailService;
use think\admin\Controller;
use think\facade\Db;
use think\facade\Session;
use think\facade\Log;
use think\facade\Mail;

class Member extends Base{

    /**
     * @name:个人中心
     * @author:Sam
     * @date:2024-09-02
     * @param:[string] param [desc]
    */
    public function index(){
        $this->check_login();
        $this->user_info = MallUsers::where('id',$this->uid)->find();
        return $this->fetch();
    }

    //修改用户信息
    public function update_user(){
        $this->check_login();
        $data = $this->_vali([
            'first_name.require'      => 'first_name cannot be empty!',
            'last_name.require'       => 'last_name cannot be empty!',
            'birthday.require'        => 'birthday cannot be empty!',
            'email.require'           => 'email cannot be empty!',
            'email.email'             => 'email format error!',
            'phone.require'           => 'phone cannot be empty!!',
        ]);
        $user = MallUsers::where('id',$this->uid)->find();
        if(MallUsers::where('email',$data['email'])->where('id','<>',$this->uid)->find()){
            return $this->error('email Already Exists!');
        }
        if(MallUsers::where('phone',$data['phone'])->where('id','<>',$this->uid)->find()){
            return $this->error('phone Already Exists!');
        }
        $user->first_name = $data['first_name'];
        $user->last_name  = $data['last_name'];
        $user->birthday   = $data['birthday'];
        $user->email      = $data['email'];
        $user->phone      = $data['phone'];
        $res = $user->save();
        return $res ? $this->success('修改成功') : $this->error('修改失败');
    }

    /**
     * @name:修改尺寸信息
     * @param:[string] param [desc]
    */
    public function my_size(){
        $this->check_login();
        if(request()->isGet()){
            $this->size = MallBraSize::field('id,size as title')->select();
            $this->user_info = MallUsers::where('id',$this->uid)->find();
            return $this->fetch();
        }else{
            $data = $this->_vali([
                'bra_size.require'      => 'size cannot be empty!',
                'panties_size.require'  => 'size cannot be empty!',
            ]);
            $user = MallUsers::where('id',$this->uid)->find();
            $user->bra_size = $data['bra_size'];
            $user->panties_size = $data['panties_size'];
            $res = $user->save();
            return $res ? $this->success('修改成功') : $this->error('修改失败');
        }
    }

    /**
     * @name:支付信息
     * @param:[string] param [desc]
    */
    public function payment(){
        $this->check_login();
        if(request()->isGet()){
            $this->user_info = MallUsers::where('id',$this->uid)->find();
            return $this->fetch();
        }else{
            
        }
    }
    /**
     * @name:我的地址信息
     * @param:[string] param [desc]
    */
    public function my_address(){
        $this->check_login();
        if(request()->isGet()){
            $this->address_list = MallUsers::where('id',$this->uid)->find();
            $this->user_info = MallUsers::where('id',$this->uid)->find();
            return $this->fetch();
        }else{
            $data = $this->_vali([
                'street.require'      => 'street cannot be empty!',
                'city.require'        => 'city cannot be empty!',
                'description.require' => 'description cannot be empty!',
                'state.require'       => 'state cannot be empty!',
                'post_code.require'    => 'post_code cannot be empty!',
            ]);
            $user = MallUsers::where('id',$this->uid)->find();
            $user->street      = $data['street'];
            $user->city        = $data['city'];
            $user->description = $data['description'];
            $user->state       = $data['state'];
            $user->post_code    = $data['post_code'];
            $res = $user->save();
            return $res ? $this->success('修改成功') : $this->error('修改失败');
        }
    }

    //我的收藏
    public function collect(){
        $this->check_login();
        $this->user_info = MallUsers::where('id',$this->uid)->find();
        $list     = MallUserActionCollect::with(['goods'])->where('unid',$this->uid)->order('id desc')->select();
        if(count($list)){
            foreach($list as $k=>&$value){
                if(!$value->ghash){
                    $value->ghash = MallGoodsItem::where('gcode',$value->gcode)->value('ghash');
                }
            }
        }
        $this->list = $list;
        return $this->fetch(); 
    }
 
    /**
     * @name:会员注册
     * @author:Sam
     * @date:2024-08-31
     * @param:[string] param [desc]
    */
    public function register()
    {
        if ($this->app->request->isGet()) {

            $userID = $this->app->session->get('uid');
        
            if (!empty($userID)) {
                $this->redirect(sysuri('/login'));
            } else {
                $this->fetch();
            }
        }else{
            $data = $this->_vali([
                'email.require'           => 'email is exist!',
                'first_name.require'      => 'first_name cannot be empty!',
                'last_name.require'       => 'last_name cannot be empty!',
                'birthday.require'        => 'birthday cannot be empty!',
                'password.min:6'          => 'password cannot be less than 6 characters!',
                'email.email'             => 'email format error!',
                'confirmPassword.require' => 'confirmPassword cannot be empty!',
            ]);
   
            if($data['password'] != $data['confirmPassword']){
                $this->error('login password and confirm password are inconsistent!');
            }
            unset($data["confirmPassword"]);
            /*! 用户信息验证 */
            $map = ['email' => $data['email']];
           
            $user = MallUsers::mk()->where($map)->findOrEmpty();
            if (!$user->isEmpty()) {
                $this->error('email Already Exists!');
            }
            $data['first_name']  = $data['first_name'];
            $data['last_name']   = $data['last_name'];
            $data['birthday']    = $data['birthday'];
            $data['email']       = $data['email'];
            $data['username']    = $data['email'];
            $data['password']    = md5($data['password'].'mrbut123456789');
            $data['create_time'] = date("Y-m-d H:i:s");
            $data['update_time'] = date("Y-m-d H:i:s");
            unset($data['confirmPassword'],$data['code']);
            $newUserId = $this->app->db->table("mall_users")->insertGetId($data);
            if($newUserId > 0){
                $userInfo = $this->app->db->table("mall_users")->where(['id'=>$newUserId])->find();
                $this->app->session->set('userInfo', $userInfo);
                $this->app->session->set('uid', $newUserId);
                return $this->success('REGISTER SUCCESS','/login');
            }
            return $this->error('REGISTER FAIL');
        }

        return $this->fetch('register');
    }

    /**
     * @name:发送验证码
     * @author:Sam
     * @date:2024-09-01
     * @param:[string] param [desc]
    */
    public function send_email(){
        $this->check_login();
        $data = $this->_vali([
            'email.require'   => 'Email Cannot Be Empty!',
        ]);
        $user = MallUsers::mk()->where('id',$this->uid)->findOrEmpty();
        if ($user->isEmpty()) {
            $this->error('Account Not Exists!');
        }
        if($user->email != $data['email']){
            $this->error('The email address is inconsistent with the registered email address!');
        }
        $code = mt_rand(111111,999999);
        // 发送邮件
        $subject = 'Your Verification Code';
        $body = <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Verification Code</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f9f9f9;
            margin: 0;
            padding: 0;
        }
        .email-container {
            max-width: 600px;
            margin: 20px auto;
            background: #ffffff;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .email-header {
            background-color: #4caf50;
            color: #ffffff;
            text-align: center;
            padding: 20px;
            font-size: 24px;
            font-weight: bold;
        }
        .email-body {
            padding: 30px;
            color: #333333;
            text-align: center;
        }
        .verification-code {
            font-size: 36px;
            font-weight: bold;
            color: #4caf50;
            margin: 20px 0;
        }
        .email-footer {
            padding: 20px;
            background-color: #f1f1f1;
            color: #666666;
            font-size: 14px;
            text-align: center;
        }
        .email-footer a {
            color: #4caf50;
            text-decoration: none;
        }
    </style>
</head>
<body>
    <div class="email-container">
        <div class="email-header">
            Verification Code
        </div>
        <div class="email-body">
            <p>Hello,</p>
            <p>Your verification code is:</p>
            <div class="verification-code">{$code}</div>
            <p>Please use this code to complete your verification. This code is valid for <strong>5 minutes</strong>.</p>
            <p style="color: red; font-weight: bold;">Do not share this code with anyone.</p>
        </div>
        <div class="email-footer">
            <p>If you did not request this code, please ignore this email or <a href="#">contact support</a>.</p>
            <p>Thank you for using our service!</p>
        </div>
    </div>
</body>
</html>
HTML;
        // 发送邮件
        $mcode_service = EmailService::sendMail($data['email'], $subject, $body);
        // $mcode_service = true;
        if($mcode_service){
            //发送成功
            cache($data['email'],$code,300);
            return $this->success('SEND SUCCESS');
        }else{
            return $this->error('SEND FAIL');
        }
    }



    /**
     * @name:退出登录
     * @author:Sam
     * @date:2024-06-09
     * @param:[string] param [desc]
    */
    public function logout(){
        Session::delete('userInfo');
        Session::delete('uid');
        $this->redirect(url('index/index/index'));
    }

    /**
     * @name:登录
     * @author:Sam
     * @date:2024-09-01
     * @param:[string] param [desc]
    */
    public function login()
    {

        if ($this->app->request->isGet()) {
            $this->title = '系统登录';
            $this->fetch();
        } else {
            $data = $this->_vali([
                'username.require' => 'Username Cannot Be Empty!',
                'password.require' => 'Password Cannot Be Empty!',
            ]);

            /*! 用户信息验证 */
            $map  = [];
            $map[] = ['email|username', '=', $data['username']];
            $map[] = ['deleted', '=', 0];
            $user = MallUsers::where($map)->find();
            if (!$user) {
                $this->app->session->set("LoginInputSessionError", true);
                $this->error('Account Or Password Error, Please Re-enter!');
            }
            $user->save();
            if (md5($data['password'].'mrbut123456789') !== $user['password']) {
                $this->app->session->set("LoginInputSessionError", true);
                // $this->error('Account Or Password Error, Please Re-enter!');
            }
            $this->app->session->set('userInfo', $user->toArray());
            $this->app->session->delete("LoginInputSessionError");
            $this->app->session->set('uid', $user['id']);
            return $this->success('login Success', '/index');
        }
    }

    /**
     * @name:订阅信息
     * @param:[string] param [desc]
    */
    public function subscriptions(){
        $this->check_login();
        $this->user_info = MallUsers::where('id',$this->uid)->find();
        return $this->fetch();
    }

    /**
     * @name:账号信息
     * @author:Sam
     * @date:2024-09-02
     * @param:[string] param [desc]
    */
    public function account(){
        $this->check_login();
        if(request()->isGet()){
            
            return $this->fetch();
        }else{
            $data = request()->post();
            if(!empty($data['area'])){
                $arr = explode('/',$data['area']);
                if(count($arr)){
                    $data['province'] = $arr[0];
                    $data['city']     = $arr[1];
                    $data['area']     = $arr[2];
                }
            }
            $uid  = $this->app->session->get('uid');
            $res = MallUsers::where('id',$uid)->update($data);
            return $res ? $this->success('修改成功') : $this->error('修改失败');
        }
    }

    /**
     * @name:修改密码
     * @author:Sam
     * @date:2024-09-03
     * @param:[string] param [desc]
    */
    public function change_password(){
        $this->check_login();
        if(request()->isGet()){
            $this->user_info = MallUsers::where('id',$this->uid)->find();
            return $this->fetch();
        }else{
            $data = $this->_vali([
                'email_code.require'   => 'Email Code Cannot Be Empty!',
                'email.require'        => 'Email Cannot Be Empty!',
                'password.require'    => 'Password Cannot Be Empty!',
                'password.min:6'      => 'Password Cannot Be Less Than 6 Characters!',
            ]);
           
            $user = MallUsers::where('id',$this->uid)->find();
            if (md5($data['password'].'mrbut123456789') == $user['password']) {
                $this->error('New Password Cannot Be The Same As The Old Password');
            }
            if(cache($data['email']) != $data['email_code']){
                $this->error('Verification Code Error');
            }
            $user->password = md5($data['password'].'mrbut123456789');
            $res = $user->save();
            return $res ? $this->success('修改成功') : $this->error('修改失败');
        }
    }


    //订阅
    public function subscription(){
        $this->subscription = ConfigService::getPage('subscription');
        $this->subscription_list         = MallSubscription::select();
        return $this->fetch();
    }

    
}